import React, { Component } from 'react'
import { connect } from 'dva';
import { Table } from 'antd';

export interface Props {
  dispatch?: Function,
  onChange?: Function,
  children?: React.ReactNode,
  loading?: boolean,
  problemList?: {
    data: Array<any>,
    dataCnt: number
  },
  buttons?: Array<any>,
  dict?: object,
  isReset?: any
}

const ONE_PAGE_SIZE = 10;

@connect(({ unit_template, loading }) => ({
  problemList: unit_template.problemList || {},
  loading: loading.effects['unit_template/queryProblemPage']
}))
class XlPosition extends Component<Props, any> {
  constructor(props) {
    super(props);
  }
  state = {
    current: 1,
    selectedRowKeys: []
  };

  queryData(offset = 1, size = ONE_PAGE_SIZE) {
    const { dispatch } = this.props;
    dispatch({
      type: 'unit_template/queryProblemPage',
      payload: {
        pageNum: offset,
        pageSize: size,
        checkType: '1'
      },
    });
  }

  onSelectChange = (selectedRowKeys, rowData) => {
    this.setState({
      selectedRowKeys: selectedRowKeys
    }, () => {
      const { problemList = {data: [], dataCnt: 0} } = this.props;
      const { data = [] } = problemList;

      const ans = selectedRowKeys.map(it => data[+it]);
      this.props.onChange(ans);
    });
  };

  componentDidMount() {
    this.queryData();
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.isReset) {
      this.setState({
        selectedRowKeys: []
      })
    }
  }

  render() {
    const { current } = this.state;
    const { buttons, problemList = {data: [], dataCnt: 0} } = this.props;
    const btnList = {};
    if(Array.isArray(buttons)) {
      buttons.forEach(item => {
        btnList[item.name] = item.name
      });
    }

    const { data = [], dataCnt } = problemList;
    const ans = data && Array.isArray(data) ? data.map((item, index) => ({
        key: index,
        itemList: item.itemList ? item.itemList : '',
        id: item.id,
        name: item.name,
        typeName: item.typeName ? item.typeName : '/'
      })
    ) : [];
    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      showQuickJumper: true,
      pageSize: ONE_PAGE_SIZE,
    };
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys ,
      hideDefaultSelections: true,
      onChange: this.onSelectChange
    };
    const columns = [{
      title: '序号',
      dataIndex: 'id'
    }, {
      title: '问题名称',
      dataIndex: 'name'
    }, {
      title: '问题类型',
      dataIndex: 'typeName'
    }];
    return (
      <div>
        <Table
          columns={columns}
          pagination={pagination}
          dataSource={ans}
          bordered
          loading={this.props.loading}
          rowSelection={ rowSelection }
        />
      </div>
    );
  }
}

export default XlPosition;
